package com.ytlz.dmcs.model.system.view;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mongodb.BasicDBObject;
import com.mongodb.DBRef;
import com.ytlz.dmcs.model.system.entity.SysObject;
import com.ytlz.dmcs.model.system.entity.SysUser;

@Controller
@RequestMapping("datalist")
public class DataListView extends BaseView{
		
	
	
	@RequestMapping(method={RequestMethod.GET,RequestMethod.POST})
	public String index(HttpServletRequest request,Model model,@RequestParam(value="type" ,required=true) String type) {
		SysObject obj = this.getSysObjectDao().findByName(type);
		model.addAttribute("datatype", type);
		model.addAttribute("datatitle",obj.getLabel());
	
		model.addAttribute("attributes", obj.getFields());
		model.addAttribute("queryattributes", filterQueryAttributes(obj.getFields()));
		return getIndexPage();
	}
	
	protected String getIndexPage() {
		return "datalist";
	}
	
	@RequestMapping("save")
	@ResponseBody
	public Map<String,Object> saveData(HttpServletRequest request,@RequestParam(value="type" ,required=true) String type){
		
		
		Enumeration<String> formnames = request.getParameterNames();
		BasicDBObject obj = new BasicDBObject();
		while (formnames.hasMoreElements()) {
			String name = formnames.nextElement();
			if(name.startsWith("form.")) {
				obj.append(name.replace("form.", ""), request.getParameter(name));
			}
		}
		obj.append("create_date", new Date());
		obj.append("modify_date", new Date());
		SysUser currentUser = this.getCurrentUser();
		obj.append("create_owner", new DBRef("sys_user", currentUser.getId()));
		this.getMongoTemplate().save(obj, type);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("message", 1);
		return result;
	}
	
}
